package com.wky.stusys.dao.impl;

import java.util.List;

import com.wky.common.dao.impl.CommonDaoImpl;
import com.wky.common.page.Page;
import com.wky.common.query.QueryInfo;
import com.wky.common.util.Tools;
import com.wky.stusys.dao.IStudentDao;
import com.wky.stusys.entity.StuCou;
import com.wky.stusys.entity.Student;
import com.wky.stusys.query.StuSysQueryInfo;

public class StudentDaoImpl extends CommonDaoImpl implements IStudentDao {

	private Page<?> getMyPage(QueryInfo info, String hql) {
		if (info.getNotPage() != null && info.getNotPage().booleanValue()) {
			List<?> data = this.executeSql(hql);
			return this.putDataToPage(data);
		} else {
			return super.find(hql, info.getPageNumber().intValue(), info
					.getPageSize().intValue());
		}
	}

	private Page<?> getMyPage(QueryInfo info, String hql, Object[] condition) {
		if (info.getNotPage() != null && info.getNotPage().booleanValue()) {
			List<?> data = this.executeSql(hql, condition);
			return this.putDataToPage(data);
		} else {
			return super.find(hql, condition, info.getPageNumber().intValue(),
					info.getPageSize().intValue());
		}
	}

	public void updateStudent(Student student) {
		this.save(student);
	}

	@SuppressWarnings("unchecked")
	public Page<StuCou> findStudentScorePage(StuSysQueryInfo info) {
		Object[] values = new Object[50];
		int idx = 0;

		StringBuffer hql = new StringBuffer();
		hql.append("from ").append(StuCou.class.getName())
				.append(" as sc where 1=1 ");

		if (info.getStuId() != null) {
			hql.append(" and sc.stuId = ? ");
			values[idx++] = info.getStuId();
		}

		if (info.getTeaId() != null) {
			hql.append(" and sc.teaId = ? ");
			values[idx++] = info.getTeaId();
		}

		if (Tools.isNotEmptyString(info.getCouName())) {
			hql.append(" and sc.course.couName like ? ");
			values[idx++] = "%" + info.getCouName() + "%";
		}

		if (Tools.isNotEmptyString(info.getTeaName())) {
			hql.append(" and sc.teacher.teaName like ? ");
			values[idx++] = "%" + info.getTeaName() + "%";
		}

		if (info.getScoreFront() != null) {
			hql.append(" and sc.score >= ? ");
			values[idx++] = info.getScoreFront();
		}

		if (info.getScoreBack() != null) {
			hql.append(" and sc.score <= ? ");
			values[idx++] = info.getScoreBack();
		}

		hql.append(" order by sc.course.couId asc");

		if (idx > 0) {
			Object[] condition = new Object[idx];
			System.arraycopy(values, 0, condition, 0, idx);
			return (Page<StuCou>) this.getMyPage(info, hql.toString(), condition);
		}
		return (Page<StuCou>) this.getMyPage(info, hql.toString());
	}

	public Student findStudent(StuSysQueryInfo info) {
		return (Student) this.load(Student.class, info.getStuId());
	}

}
